package com.example.springbootdemo.impot;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

// 该方式可配置复杂的逻辑，动态导入bean
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    // BeanDefinitionRegistry: 所有bean的定义，可注册、移除、获取所有bean
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // @import 注解所在类
        System.out.println(importingClassMetadata);

        // 判断是否包含bean定义
        boolean b = registry.containsBeanDefinition("com.example.springbootdemo.impot.MyImportDemo");
        System.out.println("是否包含MyImportDemo的bean：" + b);

        // 删除bean
        registry.removeBeanDefinition("com.example.springbootdemo.impot.MyImportDemo");

        // 注册bean
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(MyImportDemo.class);
        registry.registerBeanDefinition("beanName",rootBeanDefinition);

        // bean 数量
        System.out.println("一共有bean的数量为：" + registry.getBeanDefinitionCount());

    }
}
